package com.moli.iov.protocol.util;

import com.moli.iov.protocol.codec.DataDecoder;
import com.moli.iov.protocol.model.VehicleLoginReq;
import com.moli.iov.protocol.model.VehicleRegisterReq;
import com.moli.iov.protocol.model.realtime.RealTimeInfoReq;
import com.moli.iov.protocol.model.realtime.VehicleGpsReq;
import com.moli.iov.util.ByteArrayUtil;
import com.moli.iov.util.GsonUtil;
import com.moli.iov.util.NumberUtil;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class ProtocolUtil {


    /**
     * 将报文对象转换为业务json
     */
    public static String buildJson(RealTimeInfoReq realTimeInfoReq) {

        if (realTimeInfoReq != null) {
            Map<String, Object> map = new HashMap<String, Object>();

            //GPS数据
            VehicleGpsReq gpsReq = realTimeInfoReq.getVehicleGpsReq();

            if (gpsReq != null) {
                map.put("vehicleGps", gpsReq);
            }
            System.out.println(GsonUtil.toJsonWithSerializeNulls(map));
            return GsonUtil.toJsonWithSerializeNulls(map);
        }
        return null;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, Exception {

        List<String> list = ProtocolUtil.readToString("D:\\Internet_of_Vehicles\\iov-common\\iov-common-protocol\\src\\main\\java\\com\\moli\\iov\\protocol\\util\\pro.txt");

        for (String str : list) {
            System.out.println(str);
            byte[] bytes = ByteArrayUtil.hexStringToBytes(str);
            parseLoginReq(bytes);
        }

//		parseLoginReq(bytes);

//        parse(s);
    }

    private static String parse(String report) {
        StringBuilder sb = new StringBuilder(report);
        System.out.println(sb.substring(0, 4));
        System.out.println(sb.substring(4, 6));
        System.out.println(sb.substring(6, 8));
        System.out.println(sb.substring(8, 42));
        System.out.println(sb.substring(42, 44));
        System.out.println(sb.substring(44, 48));
        System.out.println(sb.substring(48, 60));
//        System.out.println(sb.substring(60, 62));

        System.out.println(parseData(sb.substring(60)));

        return null;
    }

    private static String parseData(String data) {
        switch (data.substring(0, 2)) {
            case "01":
                System.out.println(data.substring(0, 42));
                return data.substring(42);
            case "02":

                return data;
            case "07":

                return data;
            default:
                return data;
        }
    }


    private static Object signChange(Object data, Class<?> target) {
        if (data instanceof Byte) {
            byte tByte = NumberUtil.toByte(data);
            if (Byte.class.isAssignableFrom(target)) {
                return (byte) (tByte & 0xFF);
            } else if (Short.class.isAssignableFrom(target)) {
                return UnsignedNumberUtil.toUnsignedByteValue(tByte);
            } else if (Integer.class.isAssignableFrom(target)) {
                return UnsignedNumberUtil.toUnsignedShortValue((short) (tByte));
            } else if (Long.class.isAssignableFrom(target)) {
                return UnsignedNumberUtil.toUnsignedIntValue((int) (tByte));
            }
        }
        return data;
    }


    static <T> T parse(Class<T> clazz, byte[] bytes) throws InstantiationException, IllegalAccessException, Exception {
        DataDecoder<T> decoder = new DataDecoder<>();
        T a = clazz.newInstance();
        decoder.decode(a, bytes);
        System.out.println(a.toString());
        return a;
    }

    public static <T> T parseP(Class<T> clazz, byte[] bytes) throws Exception {
        return parse(clazz, bytes);
    }

    static void parseRegister(byte[] bytes) {
        VehicleRegisterReq vehicleRegisterReq = new VehicleRegisterReq();
        DataDecoder<VehicleRegisterReq> decoder = new DataDecoder<>();
        try {
            decoder.decode(vehicleRegisterReq, bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(vehicleRegisterReq.toString());
    }

    public static void parseLoginReq(byte[] bytes) {
        VehicleLoginReq vehicleLoginReq = new VehicleLoginReq();
        DataDecoder<VehicleLoginReq> decoder = new DataDecoder<>();
        try {
            decoder.decode(vehicleLoginReq, bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(vehicleLoginReq.toString());
    }

    static void parseRealTimeReq(byte[] bytes) {
        RealTimeInfoReq realTimeInfoReq = new RealTimeInfoReq();
        DataDecoder<RealTimeInfoReq> decoder = new DataDecoder<>();
        try {
            decoder.decode(realTimeInfoReq, bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(realTimeInfoReq.getVehicleAllReq().getOdometer() + " " + realTimeInfoReq.getCollectDate());
//        if(realTimeInfoReq.getVehicleAllReq().getOdometer()>0){
//        System.out.println(realTimeInfoReq.getVehicleAllReq().getOdometer() + " " + realTimeInfoReq.getCollectDate());
            System.out.println(realTimeInfoReq.toString());
//        }
    }

    public static List<String> readToString(String fileName) throws IOException {

        List<String> list = new ArrayList<>();
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        String line = "";
        String[] arrs = null;
        while ((line = br.readLine()) != null) {
            line = line.replaceAll("\r|\n", "");
            line = line.replaceAll(" ", "");
//            if(line.indexOf("[RECV]:232302")>=0 || line.indexOf("[RECV]:232303")>=0){
                list.add(line.substring(line.indexOf("[RECV]:")+"[RECV]:".length()));
//            }
        }
        br.close();
        fr.close();
        return list;
    }

    public static Set<String> readToString1(String fileName) throws IOException {

        Set<String> list = new HashSet<>();
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        String line = "";
        String[] arrs = null;
        while ((line = br.readLine()) != null) {
            line = line.replaceAll("\r|\n", "");
            line = line.replaceAll(" ", "");
            if(line.indexOf("iccid不相同")>0 ){
                list.add(line.substring(line.indexOf("vin:")+"vin:".length(),line.indexOf("，iccid:")));
            }
        }
        br.close();
        fr.close();
        return list;
    }

    public static String str2Bytes(String str) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        int i = 1;
        while (!str.equals("")) {
            sb.append(str.substring(0, 2));
//			str = str.substring(3);
            i++;
            if (i > 1) {
                break;
            }

        }
        sb.append("}");

        return sb.toString();
    }
}
